<?php


namespace app\shop\service\order;


use app\enterprise\model\Message;
use app\shop\common\consts\Consts;
use app\shop\model\chat\GroupUserModel;
use app\shop\model\config\TypeBusinessModel;
use app\shop\model\config\TypeDesignModel;
use app\shop\model\config\TypeFieldModel;
use app\shop\model\config\TypePayModel;
use app\shop\model\config\TypeProgramModel;
use app\shop\model\file\FileModel;
use app\shop\model\order\OrderComplainModel;
use app\shop\model\order\OrderDesignModel;
use app\shop\model\order\OrderModel;
use app\shop\model\order\OrderSubModel;
use app\shop\model\user\AdminRoleModel;
use app\shop\model\user\ChatUserModel;
use app\shop\model\user\DepartmentModel;
use app\shop\model\user\DesignScoreModel;
use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\BaseService;
use app\shop\service\chat\ChatGroupUserService;
use app\shop\service\chat\ChatUserService;
use app\shop\service\until\FileService;
use app\shop\service\user\FriendService;
use app\shop\service\user\GroupService;
use app\shop\validate\OrderValidate;
use GatewayClient\Gateway;
use think\facade\Db;
use think\facade\Log;
use think\Request;

class OrderService extends BaseService
{

    public static function getInstance()
    {
        return new OrderModel();
    }

    public function __construct()
    {
    }

    /**
     * 创建订单
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public static function createOrder($data)
    {
        Db::startTrans();
        try {

            Validate(OrderValidate::class)->scene('add')->check($data);

            $userInfo = UserModel::where('mobile', $data['mobile'])->find();
            if (!$userInfo) {
                throw new \Exception('客户不存在');
            }
            if ($userInfo['role_id'] != Consts::CUSTOMER_ID) {
                throw new \Exception('客户角色错误');
            }
            $data['order_sn'] = isset($data['order_sn']) ? $data['order_sn'] : createOrderSn('order', 'order_sn', 'SJ');
            $data['user_id'] = $userInfo['user_id'];
            $order = self::getInstance();
            $order->save($data);

            // 建立群聊
            $service = new ChatGroupUserService();
            $service->createGroup($data['user_id'], $order->id, $order['order_name']);
            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollBack();
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 修改订单
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public static function updateOrder($data)
    {
        try {
            Validate(OrderValidate::class)->scene('edit')->check($data);

            $userInfo = UserModel::where('mobile', $data['mobile'])->find();
            if (!$userInfo) {
                throw new \Exception('客户不存在');
            }
            if ($userInfo['role_id'] != Consts::CUSTOMER_ID) {
                throw new \Exception('客户角色错误');
            }
            $data['user_id'] = $userInfo['user_id'];

            // 给客户和销售添加好友
            $order = self::getInstance()::find($data['id']);
            if ($order['update_count']) {
                throw new \Exception('只能修改一次');
            }
            $data['update_count'] += 1;
            return $order->save($data);
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 指派销售
     * @param $orderId
     * @param $userId
     * @return bool
     * @throws \Exception
     */
    public static function assignSalesman($orderId, $userId)
    {
        try {

            $orderInfo = self::getInstance()::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if (!$userId) {
                throw new \Exception('请选择销售');
            }
            if ($userId == $orderInfo['sale_id']) {
                throw new \Exception('分配销售与之前销售相同');
            }

            $orderInfo->sale_id = $userId;
            if ($orderInfo->design_id) {
                $orderInfo->order_status = OrderModel::UNDERWAY;
            }
            $orderInfo->save();

            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 指派设计师
     * @param $userInfo
     * @param $orderId
     * @param $userId
     * @param $orderName
     * @return bool
     * @throws \Exception
     */
    public static function assignDesigner($userInfo, $orderId, $userId, $orderName = '')
    {
        try {
            if ($userInfo['role_id'] != Consts::ASSIGN_ORDER && $userInfo['role_id'] != Consts::ADMIN_ROLE_ID) {
                throw new \Exception('您没有派单权限');
            }
            $orderInfo = self::getInstance()::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if (!$userId) {
                throw new \Exception('请选择设计师');
            }
            $oldDesignId = $orderInfo['design_id'];
            if ($userId == $oldDesignId) {
                throw new \Exception('分配设计师与之前设计师相同');
            }
            $orderInfo->design_id = $userId;
            if ($orderInfo->sale_id) {
                $orderInfo->order_status = OrderModel::UNDERWAY;
            }
            if ($orderName) {
                $orderInfo->order_name = $orderName;
            }
            $orderInfo->save();
            // 判断群聊是否存在
            $chatSign = generate_chat_sign($orderInfo['user_id'], 0, $orderInfo['id']);
            $chatInfo = ChatUserModel::where('chat_sign', $chatSign)->find();
            if (!$chatInfo) {
                $service = new ChatGroupUserService();
                $service->createGroup($orderInfo['user_id'], $orderId, $orderInfo->order_name);
            }
            // 设计师进入群聊
            $chatUserService = new ChatUserService();
            $chatUserService->joinGroup($chatSign, $userId);

            // 踢出原来的设计师
            if ($oldDesignId) {
                $chatUserService->kickOutGroup($chatSign, [$oldDesignId]);
            }

            // 订单设计师变更记录
            $orderDesign = new OrderDesignModel();
            $orderDesign->order_id = $orderId;
            $orderDesign->design_id = $userId;
            $orderDesign->save();

            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取创建订单时的选项
     * @return mixed
     * @throws \Exception
     */
    public static function getCreateOrderOptionArr()
    {
        try {
            // 设计类型
            $data['designArr'] = TypeDesignModel::select();
            // 业务类型
            $data['businessArr'] = TypeBusinessModel::select();
            // 扩展字段
            $data['fieldArr'] = TypeFieldModel::where('name', '<>', '')->select()->toArray();
            // 付款方式
            $data['payArr'] = TypePayModel::select();
            // 设计项目
            $data['programArr'] = TypeProgramModel::select();
            // 设计师
            $data['designerArr'] = UserModel::whereIn('role_id', [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID])
                ->where('status', 1)
                ->field('user_id,realname')
                ->select()
                ->toArray();
            // 销售
            $data['saleArr'] = UserModel::where('role_id', Consts::SALE_ID)
                ->where('status', 1)
                ->field('user_id,realname')
                ->select()
                ->toArray();
            return $data;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 订单列表
     * @param $userInfo
     * @param string $orderStatus
     * @param string $keyword
     * @param int $isComplaint
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public static function getOrderList($userInfo, $orderStatus = '', $keyword = '', $isComplaint = 0, $page = 1, $limit = 10, $type = 0)
    {
        try {
            $userId = $userInfo['user_id'];
            $roleId = $userInfo['role_id'];
            $where = [];
            if ($keyword) {
                if ($type == 0) {
                    $where[] = ['mobile|order_name|design_need|order_sn', 'like', "%{$keyword}%"];
                } else {
                    $arr = UserModel::where('realname', 'like', "%{$keyword}%")->column('mobile');
                    if (!$arr) {
                        $where[] = ['mobile', '=', -1];
                    } else {
                        $where[] = ['mobile', 'in', $arr];
                    }
                }
            }
            if ($isComplaint) {
                $where[] = ['is_complaint', 'in', [1, 2]];
            }
            if ($orderStatus != '' && $orderStatus != 10000 && $orderStatus != 10001) {
                $where[] = ['order_status', '=', $orderStatus];
            }
            // 根据角色ID进行筛选
            if ($roleId == Consts::CUSTOMER_ID) {
                $where[] = ['user_id', '=', $userId];
                $where[] = ['pid', '=', 0];
            }
            if ($roleId == Consts::SALE_ID) {
                $where[] = ['sale_id', '=', $userId];
            }
            if ($roleId == Consts::DESIGN_ID) {
                $where[] = ['design_id', '=', $userId];
            }
            if ($roleId == Consts::DESIGN_LEADER_ID) {
                if ($orderStatus == 10000) {
                    $designArr = UserModel::where('department_id', $userInfo['department_id'])
                        ->where('role_id', Consts::DESIGN_ID)
                        ->column('user_id');
                    $where[] = ['design_id', 'in', $designArr];
                } else {
                    $where[] = ['design_id', '=', $userId];
                }
            }
            $orderField = 'id';
            $orderSort = 'desc';
            if ($isComplaint) {
                $orderField = 'complaint_time';
                $orderSort = 'desc';
            }
            $list = OrderModel::where($where)
                ->order($orderField, $orderSort)
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['user_name'] = UserModel::where('user_id', $v['user_id'])->value('realname', ''); // 客户名称
                $v['design_id'] = UserModel::where('user_id', $v['design_id'])->value('realname', ''); // 设计师名称
                $v['sale_id'] = UserModel::where('user_id', $v['sale_id'])->value('realname', ''); // 销售

                $designNeedFileArr = FileService::getFileArray($v['design_need_file']); // 需求文件
                $v['design_need_file_arr'] = $designNeedFileArr['file'];
                $v['design_need_file_img'] = $designNeedFileArr['img'];

                $replenishNeedFileArr = FileService::getFileArray($v['replenish_need_file']); // 补充需求文件
                $v['replenish_need_file_arr'] = $replenishNeedFileArr['file'];
                $v['replenish_need_file_img'] = $replenishNeedFileArr['img'];

                $v['remarks_files_arr'] = FileService::getFileArr($v['remark_file_id']); // 备注的文件
                $v['create_time'] = date('Y-m-d', strtotime($v['create_time'])); // 订单创建时间
                // 关联订单数量
                $v['relation_order_count'] = OrderModel::where('user_id', $v['user_id'])
                    ->where('design_id', '<>', $userId)
                    ->where('design_id', '<>', 0)
                    ->where('id', '<>', $v['id'])
                    ->count();
                // 子订单数量
                $v['sub_order_count'] = OrderModel::where('pid', $v['id'])->count();
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 指派订单列表
     * @param $userInfo
     * @param string $orderStatus
     * @param string $keyword
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public static function getAssignOrderList($userInfo, $orderStatus = '', $keyword = '', $page = 1, $limit = 10)
    {
        try {
            $roleId = $userInfo['role_id'];
            $where = [];
            if ($keyword) {
                $where[] = ['mobile|order_name|design_need|order_sn', 'like', "%{$keyword}%"];
            }
            if ($orderStatus == '') {
                // 全部
                $where[] = ['order_status', 'in', [0, 1]];
            } else {
                if ($orderStatus == 0) {
                    // 未指派
                    $where[] = ['order_status', '=', 0];
                } else if ($orderStatus == 1) {
                    // 已指派
                    $where[] = ['order_status', '=', 1];
                } else if ($orderStatus == 2) {
                    // 更换指派
                    $where[] = ['order_status', 'in', [1, 4]];
                }
            }
            if ($roleId != Consts::SERVICE_LEADER_ID && $roleId != Consts::SALE_LEADER_ID) {
                $where[] = ['id', '=', 0];
            }
            $list = OrderModel::where($where)
                ->order('create_time', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['user_id'] = UserModel::where('user_id', $v['user_id'])->value('realname'); // 客户名称
                $v['design_id'] = UserModel::where('user_id', $v['design_id'])->value('realname'); // 设计师名称
                $v['sale_id'] = UserModel::where('user_id', $v['sale_id'])->value('realname'); // 销售
                $designNeedFileArr = FileService::getFileArray($v['design_need_file']); // 需求文件
                $v['design_need_file_arr'] = $designNeedFileArr['file'];
                $v['design_need_file_img'] = $designNeedFileArr['img'];

                $replenishNeedFileArr = FileService::getFileArray($v['replenish_need_file']); // 补充需求文件
                $v['replenish_need_file_arr'] = $replenishNeedFileArr['file'];
                $v['replenish_need_file_img'] = $replenishNeedFileArr['img'];

                $v['remarks_files_arr'] = FileService::getFileArr($v['remark_file_id']); // 备注的文件
                $v['create_time'] = date('Y-m-d', strtotime($v['create_time'])); // 订单创建时间
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 订单详情
     * @param $orderId
     * @param $userInfo
     * @return OrderModel|array|mixed|\think\Model|null
     * @throws \Exception
     */
    public static function getOrderDetail($orderId, $userInfo)
    {
        try {
            $order = self::getInstance()->where('id', $orderId)->find();
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            // 图片信息
            $order['invoice_img'] = $order['invoice_img'] ? FileService::getFullUrl($order['invoice_img']) : '';
            $order['due_refund_voucher'] = $order['due_refund_voucher'] ? FileService::getFullUrl($order['due_refund_voucher']) : '';
            $order['refund_voucher'] = $order['refund_voucher'] ? FileService::getFullUrl($order['refund_voucher']) : '';
            // 客户信息
            $customerInfo = UserModel::find($order['user_id']);
            $customerRoleId = $customerInfo['role_id'] ?? 0;
            $customerRoleInfo = AdminRoleModel::find($customerRoleId);
            $order['user_name'] = $customerInfo['realname'] ?? '';
            $order['user_avatar'] = $customerInfo['avatar'] ?? '';
            $order['user_role_name'] = $customerRoleInfo['role_name'] ?? '';

            // 设计师信息
            $designInfo = UserModel::find($order['design_id']);
            $designRoleId = $designInfo['role_id'] ?? 0;
            $designRoleInfo = AdminRoleModel::find($designRoleId);
            $order['design_name'] = $designInfo['realname'] ?? '';
            $order['design_avatar'] = $designInfo['avatar'] ?? '';
            $order['design_role_name'] = $designRoleInfo['role_name'] ?? '';

            // 订单投诉
            $order['complaint_list'] = OrderComplainModel::with('design')->where('order_id', $orderId)->select();
            // 订单评价
            $order['evaluate_list'] = DesignScoreModel::with('user')->where('order_id', $orderId)->select();

            // 销售信息
            $saleInfo = UserModel::find($order['sale_id']);
            $saleRoleId = $saleInfo['role_id'] ?? 0;
            $saleRoleInfo = AdminRoleModel::find($saleRoleId);
            $order['sale_name'] = $saleInfo['realname'] ?? '';
            $order['sale_role_name'] = $saleRoleInfo['role_name'] ?? '';
            $order['sale_avatar'] = $saleInfo['avatar'] ?? '';

            $order['design_type_name'] = TypeDesignModel::withTrashed()->where('id', $order['design_type'])->value('name'); // 设计类型
            $order['business_type_name'] = TypeBusinessModel::withTrashed()->where('id', $order['business_type'])->value('name'); // 业务类型
            $order['pay_type_name'] = TypePayModel::withTrashed()->where('id', $order['pay_type'])->value('name'); // 支付类型
            $order['program_id_name'] = TypeProgramModel::withTrashed()->where('id', $order['program_id'])->value('name'); // 设计项目

            $designNeedFileArr = FileService::getFileArray($order['design_need_file']); // 需求文件
            $order->design_need_file_arr = $designNeedFileArr['file'];
            $order->design_need_file_img = $designNeedFileArr['img'];

            $replenish_need_file_arr = FileService::getFileArray($order['replenish_need_file']); // 补充需求文件
            $order->replenish_need_file_arr = $replenish_need_file_arr['file'];
            $order->replenish_need_file_img = $replenish_need_file_arr['img'];

            $order['remarks_files_arr'] = FileService::getFileArr($order['remark_file_id']); // 备注的文件

            $order['create_time'] = date('Y-m-d', strtotime($order['create_time'])); // 订单创建时间

            // 订单设计师列表
            $designList = OrderDesignModel::with('design')->where('order_id', $orderId)->group('design_id')->select();
            $order['design_list'] = $designList;

            // 扩展字段
            $userRoleId = $userInfo['role_id'];
            $extendFieldArr = [];
            $fieldArr = TypeFieldModel::select();
            foreach ($fieldArr as $k => $v) {
                $field = $v['field'];
                $name = $v['name'];
                $roleIdArr = $v['role_id'] ? $v['role_id'] : [];
                if ($order[$field] && in_array($userRoleId, $roleIdArr)) {
                    $extendFieldArr[] = [
                        'title' => $name,
                        'val' => $order[$field],
                    ];
                }
            }
            $order['extend_field'] = $extendFieldArr;
            $order['order_sub_status_txt'] = OrderModel::getSubStatusTextAttr($order['order_sub_status']);
            $order['order_status_txt'] = OrderModel::getOrderTxt($order['order_status']);
            // 聊天标识
            if ($order['pid'] == 0) {
                $order['chat_sign'] = generate_chat_sign($order['user_id'], 0, $order['id']);
            } else {
                $order['chat_sign'] = generate_chat_sign($order['user_id'], 0, $order['pid']);
            }

            // 是否有子订单
            $order['has_sub_order'] = OrderModel::where('pid', $orderId)->find() ? 1 : 0;
            return $order;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 指派用户列表
     * @param $userInfo
     * @param string $keyword
     * @return UserModel[]|array|\think\Collection
     * @throws \Exception
     */
    public static function getDesignUserList($userInfo, $keyword = '')
    {
        try {
            $where = [];
            $where[] = ['status', '=', 1];
            if ($keyword) {
                $where[] = ['mobile|realname', 'like', "%{$keyword}%"];
            }
            if (!in_array($userInfo['role_id'], [Consts::SALE_LEADER_ID, Consts::DESIGN_LEADER_ID, Consts::ASSIGN_ORDER])) {
                return [];
            }
            if ($userInfo['role_id'] == Consts::SALE_LEADER_ID) {
                $childDepartment = get_child_department_id($userInfo['department_id']);
                array_push($childDepartment, $userInfo['department_id']);
                $where[] = ['role_id', '=', Consts::SALE_ID];
                $where[] = ['department_id', 'in', $childDepartment];
            }
            if ($userInfo['role_id'] == Consts::DESIGN_LEADER_ID) {
                $where[] = ['department_id', '=', $userInfo['department_id']];
                $where[] = ['role_id', '=', Consts::DESIGN_ID];
            }
            if ($userInfo['role_id'] == Consts::ASSIGN_ORDER) {
                $where[] = ['role_id', '=', Consts::DESIGN_ID];
            }
            $list = UserModel::where($where)
                ->field('department_id, user_sn, user_id, realname, mobile, avatar')
                ->select();
            foreach ($list as &$v) {
                $v['department_name'] = DepartmentModel::where('id', $v['department_id'])->value('name'); //部门名称
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 订单评价
     * @param $orderId
     * @param $evaluateInfo
     * @return bool
     * @throws \Exception
     */
    public static function evaluateOrder($orderId, $evaluateInfo)
    {
        try {
            $orderInfo = self::getInstance()->find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderStatus = $orderInfo['order_status'];
            foreach ($evaluateInfo as $value) {
                if (!$value['evaluate']) {
                    throw new \Exception('请输入评价内容');
                }
                if ($orderInfo['design_id'] == $value['design_id'] && $orderStatus == OrderModel::FINALIZE) {
                    $orderInfo->is_evaluate = 1;
                    $orderInfo->save();
                }
                $scoreModel = new DesignScoreModel();
                $scoreModel->user_id = $value['design_id'];
                $scoreModel->evaluate = $value['evaluate'];
                $scoreModel->order_id = $orderId;
                // 作品评分
                $scoreModel->work_score = isset($value['grade']) ? $value['grade'] : 0;
                // 设计师评分
                $scoreModel->score = isset($value['grade_designer']) ? $value['grade_designer'] : 0;
                // 0：7天时评价 1：定稿时评价
                $scoreModel->type = $orderStatus == 1 ? 0 : 1;
                // 0差评 1好评
                $scoreModel->good = $value['good'];
                $scoreModel->save();
                // 重新计算用户评分
                $scoreArr = DesignScoreModel::where('user_id', $value['design_id'])->column('score');
                $total = array_sum($scoreArr);
                $count = count($scoreArr) > 0 ? count($scoreArr) : 1;
                $score = intval($total / $count);
                $score = $score > 3 ? $score : 3;

                $workerScoreArr = DesignScoreModel::where('user_id', $value['design_id'])->column('work_score');
                $total1 = array_sum($workerScoreArr);
                $count1 = count($workerScoreArr) > 0 ? count($workerScoreArr) : 1;
                $score1 = intval($total1 / $count1);

                $userInfo = UserModel::find($orderInfo['design_id']);
                $userInfo->score = $score;
                $userInfo->worker_score = $score1;
                $userInfo->save();
            }
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 订单投诉
     * @param $orderId
     * @param $content
     * @return bool
     * @throws \Exception
     */
    public static function complaintOrder($orderId, $content)
    {
        try {
            $orderInfo = self::getInstance()->find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['is_complaint'] == 1) {
                throw new \Exception('投诉处理中');
            }
            $orderInfo->is_complaint = 1;
            $orderInfo->save();
            foreach ($content as $value) {
                $designId = $value['design_id'];
                if (!$designId) {
                    throw new \Exception('请选择投诉的设计师');
                }
                $content = $value['complaint_content'];
                if (!$content) {
                    throw new \Exception('请输入投诉内容');
                }
                // 投诉表
                $complaint = new OrderComplainModel();
                $complaint->order_id = $orderId;
                $complaint->design_id = $designId;
                $complaint->user_id = $orderInfo['user_id'];
                $complaint->content = $content;
                $complaint->save();
            }
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 处理订单投诉
     * @param $orderId
     * @param $designId
     * @param $solution
     * @return bool
     * @throws \Exception
     */
    public static function handleComplaintOrder($orderId, $designId, $solution)
    {
        try {
            $orderInfo = self::getInstance()->find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['is_complaint'] !== 1) {
                throw new \Exception('状态错误');
            }
            $orderInfo->is_complaint = 2;
            $orderInfo->solution = $solution;
            $orderInfo->save();

            $complaint = OrderComplainModel::where('order_id', $orderId)->where('status', 0)->find();
            $complaint->reply = $solution;
            $complaint->status = 1;
            $complaint->save();
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage() . $exception->getLine());
        }
    }

    /**
     * 修改开票信息
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public static function editInvoiceInfo($data)
    {
        try {
            $id = $data['id'];
            $orderInfo = self::getInstance()->find($id);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['is_invoice'] == 1 && $data['is_invoice'] == 0) {
                throw new \Exception('开票信息已存在');
            }
            $orderInfo->save($data);
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 设置订单子状态
     * @param $orderId
     * @param $status
     * @return bool
     * @throws \Exception
     */
    public static function setOrderSubStatus($orderId, $status)
    {
        try {
            $orderInfo = self::getInstance()::find($orderId);
            $orderInfo->order_sub_status = $status;
            return $orderInfo->save();
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 申请售后
     * @param $orderId
     * @param $userInfo
     * @return bool
     * @throws \Exception
     */
    public static function applyOrderService($orderId, $userInfo)
    {
        Db::startTrans();
        try {
            $roleId = $userInfo['role_id'];
            if (!in_array($roleId, [Consts::DESIGN_LEADER_ID, Consts::SERVICE_LEADER_ID])) {
                throw new \Exception('无操作权限');
            }
            $orderInfo = self::getInstance()::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != OrderModel::FINALIZE) {
                throw new \Exception('定稿订单才能申请售后');
            }
            $orderInfo->order_sub_status = 5;
            $orderInfo->order_status = OrderModel::SERVICE_ORDER;
            $orderInfo->save();

            // 建立群聊
            $chatUserInfo = ChatUserModel::where('order_id', $orderId)->find();
            if (!$chatUserInfo) {
                $service = new ChatGroupUserService();
                $service->createGroup($orderInfo['user_id'], $orderId, $orderInfo['order_name']);
            }

            Db::commit();
            return true;
        } catch (\Exception $exception) {
            Db::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 删除订单
     * @param $orderId
     * @param $userInfo
     * @return bool
     * @throws \Exception
     */
    public static function delOrder($orderId, $userInfo)
    {
        try {
            $orderInfo = self::getInstance()::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['order_status'] != OrderModel::WAIT_DISTRIBUTE) {
                throw new \Exception('待指派订单才能删除');
            }
            if ($userInfo['user_id'] != $orderInfo['create_uid']) {
                throw new \Exception('只能删除自己创建的订单');
            }
            return $orderInfo->delete();
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 获取用户可以设置的订单状态
     * @param $orderId
     * @param $userInfo
     * @return array
     * @throws \Exception
     */
    public static function getRoleOrderStatusArr($orderId, $userInfo)
    {
        try {
            $orderInfo = self::getInstance()::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            $orderStatus = $orderInfo['order_status'];
            $roleId = $userInfo['role_id'];
            $isSelfOrder = $userInfo['user_id'] == $orderInfo['design_id'] ? 1 : 0;

            $orderStatusArr = [];
            if ($roleId == Consts::DESIGN_ID) {
                switch ($orderStatus) {
                    case 1:
                    case 3:
                        $orderStatusArr = [
                            2 => '定稿',
                            4 => '暂停设计',
                        ];
                        break;
                    case 4:
                        $orderStatusArr = [
                            1 => '进行中',
                        ];
                        break;
                    case 7:
                        $orderStatusArr = [
                            2 => '定稿',
                            4 => '暂停设计',
                        ];
                        break;
                }
            }
            if ($roleId == Consts::DESIGN_LEADER_ID) {
                switch ($orderStatus) {
                    case 0:
                        $orderStatusArr = [
                            4 => '暂停设计',
                        ];
                        break;
                    case 1:
                        $orderStatusArr = [
                            2 => '定稿',
                            3 => '死单',
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                    case 4:
                        $orderStatusArr = [
                            1 => '进行中',
                            3 => '死单',
                            5 => '退款',
                        ];
                        break;
                    case 5:
                        $orderStatusArr = [
                            1 => '进行中',
                            3 => '死单',
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                    case 7:
                        $orderStatusArr = [
                            1 => '进行中',
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                }
            }
            if ($roleId == Consts::SERVICE_LEADER_ID) {
                switch ($orderStatus) {
                    case 0:
                    case 1:
                    case 3:
                        $orderStatusArr = [
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                    case 2:
                        $orderStatusArr = [
                            7 => '售后中',
                        ];
                        break;
                    case 4:
                        $orderStatusArr = [
                            1 => '进行中',
                            5 => '退款',
                        ];
                        break;
                    case 5:
                        $orderStatusArr = [
                            1 => '进行中',
                            3 => '死单',
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                    case 7:
                        $orderStatusArr = [
                            1 => '进行中',
                            4 => '暂停设计',
                            5 => '退款',
                        ];
                        break;
                }
            }
            $arr = [];
            if ($orderStatusArr) {
                foreach ($orderStatusArr as $k => $v) {
                    $arr[] = ['id' => $k, 'name' => $v];
                }
            }
            return $arr;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 设置订单状态
     * @param $orderId
     * @param $stateId
     * @return bool
     * @throws \Exception
     */
    public static function setOrderStatus($orderId, $stateId)
    {
        try {
            // 查询订单
            $order = OrderModel::find($orderId);
            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($stateId == OrderModel::FINALIZE) {
                // 判断是否有尾款  未付尾款不能定稿
                if ($order['residue_amount'] > 0 && $order['is_take'] == 0) {
                    throw new \Exception('未付尾款，不能定稿');
                }
                // 订单定稿时间
                $order->finalize_time = time();
            }
            // 更新订单状态
            $order->order_status = $stateId;
            $order->save();

            // 设置聊天信息
            if (in_array($stateId, [OrderModel::FINALIZE, OrderModel::REFUNDED_ORDER])) {
                $chatSign = generate_chat_sign($order['user_id'], 0, $orderId);
                $chatUserService = new ChatUserService();
                $chatUserService->dissolveGroup($chatSign);
            }
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 创建子订单
     * @param Request $request
     * @return bool
     * @throws \Exception
     */
    public function createSubOrder(Request $request)
    {
        try {
            $data = [];
            $orderId = $request->param('order_id', 0, 'int');
            if (!$orderId) {
                throw new \Exception('请选择母订单');
            }
            $orderInfo = OrderModel::find($orderId);
            if (!$orderInfo) {
                throw new \Exception('母订单不存在');
            }
            $data['pid'] = $orderId;
            $orderName = $request->param('order_name', '', 'trim');
            if ($orderName == '') {
                throw new \Exception('请填写订单名称');
            }
            $data['order_name'] = $orderName;
            $data['user_id'] = $orderInfo['user_id'];
            $data['mobile'] = $orderInfo['mobile'];
            $data['order_status'] = $request->param('order_status', 0, 'int');
            $data['order_amount'] = $request->param('order_amount', 0, 'int');
            $data['design_need'] = $request->param('design_need', '', 'trim');
            $data['design_need_file'] = $request->param('design_need_file', '', 'trim');
            $data['design_type'] = $request->param('design_type', 0, 'int');
            $data['business_type'] = $request->param('business_type', 0, 'int');
            $data['program_id'] = $request->param('program_id', 0, 'int');
            $data['remark'] = $request->param('remark', '', 'trim');
            $data['remark_file_id'] = $request->param('remark_file_id', '', 'trim');
            $data['residue_amount'] = $request->param('residue_amount', 0, 'int');
            $data['is_urgent'] = $request->param('is_urgent', 0, 'int');
            $userId = $request->middleware('userId');
            $data['sale_id'] = isset($data['sale_id']) && $data['sale_id'] ? $data['sale_id'] : $userId;
            $data['create_uid'] = $userId;
            $data['order_sn'] = isset($data['order_sn']) ? $data['order_sn'] : createOrderSn('order', 'order_sn', 'ZD');
            $subOrderModel = new OrderModel();
            $subOrderModel->save($data);
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 关联订单
     * @param $orderId
     * @return OrderModel[]|array|\think\Collection
     * @throws \Exception
     */
    public function getRelatedOrder($orderId)
    {
        try {
            $orderInfo = OrderModel::find($orderId);
            $userId = $orderInfo['user_id'];
            $list = OrderModel::where('user_id', $userId)
                ->where('design_id', '<>', $orderInfo['design_id'])
                ->where('design_id', '<>', 0)
                ->where('id', '<>', $orderId)
                ->field('id,order_name,design_id,design_need,order_sn')
                ->select();
            foreach ($list as &$value) {
                $designInfo = UserModel::find($value['design_id']);
                $value['design_name'] = $designInfo['realname'] ?? "";
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 子订单详情
     * @param $subOrderId
     * @return OrderSubModel[]|array|\think\Collection
     * @throws \Exception
     */
    public function getSubOrderDetail($subOrderId)
    {
        try {
            $order = OrderModel::find($subOrderId);
            if (!$order) {
                return [];
            }
            // 设计师信息
            $designInfo = UserModel::find($order['design_id']);
            $designRoleId = $designInfo['role_id'] ?? 0;
            $designRoleInfo = AdminRoleModel::find($designRoleId);
            $order['design_name'] = $designInfo['realname'] ?? '';
            $order['design_avatar'] = $designInfo['avatar'] ?? '';
            $order['design_role_name'] = $designRoleInfo['role_name'] ?? '';
            $order['design_type_name'] = TypeDesignModel::withTrashed()->where('id', $order['design_type'])->value('name'); // 设计类型
            $order['business_type_name'] = TypeBusinessModel::withTrashed()->where('id', $order['business_type'])->value('name'); // 业务类型
            $order['pay_type_name'] = TypePayModel::withTrashed()->where('id', $order['pay_type'])->value('name'); // 支付类型
            $order['program_id_name'] = TypeProgramModel::withTrashed()->where('id', $order['program_id'])->value('name'); // 设计项目

            $designNeedFileArr = FileService::getFileArray($order['design_need_file']); // 需求文件
            $order->design_need_file_arr = $designNeedFileArr['file'];
            $order->design_need_file_img = $designNeedFileArr['img'];

            $replenish_need_file_arr = FileService::getFileArray($order['replenish_need_file']); // 补充需求文件
            $order->replenish_need_file_arr = $replenish_need_file_arr['file'];
            $order->replenish_need_file_img = $replenish_need_file_arr['img'];

            $order['remarks_files_arr'] = FileService::getFileArr($order['remark_file_id']); // 备注的文件

            $order['chat_sign'] = generate_chat_sign($order['user_id'], 0, $order['pid']);
            return $order;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 子订单
     * @param $orderId
     * @return OrderSubModel[]|array|\think\Collection
     * @throws \Exception
     */
    public function getSubOrderList($orderId)
    {
        try {
            $list = OrderModel::where('pid', $orderId)->select();
            foreach ($list as &$value) {
                $designInfo = UserModel::find($value['design_id']);
                $value['design_name'] = $designInfo['realname'] ?? "";
            }
            return $list;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 设置订单状态
     * @param $subOrderId
     * @param $status
     * @return bool
     * @throws \Exception
     */
    public static function setSubOrderStatus($subOrderId, $status)
    {
        try {
            // 查询订单
            $order = OrderModel::find($subOrderId);
            if (!$order) {
                throw new \Exception('订单不存在');
            }

            if ($status == OrderModel::FINALIZE) {
                // 订单定稿时间
                $order->finalize_time = time();
            }
            // 更新订单状态
            $order->order_status = $status;
            $order->save();
            return true;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * 指派设计师
     * @param $userInfo
     * @param $orderId
     * @param $userId
     * @param $orderName
     * @return bool
     * @throws \Exception
     */
    public static function assignSubOrderDesigner($userInfo, $orderId, $userId, $orderName)
    {
        if ($userInfo['role_id'] != Consts::ASSIGN_ORDER && $userInfo['role_id'] != Consts::ADMIN_ROLE_ID) {
            throw new \Exception('您没有派单权限');
        }
        $orderInfo = OrderModel::find($orderId);
        if (!$orderInfo) {
            throw new \Exception('订单不存在');
        }
        if (!$userId) {
            throw new \Exception('请选择设计师');
        }
        $oldDesignId = $orderInfo['design_id'];
        if ($userId == $oldDesignId) {
            throw new \Exception('分配设计师与之前设计师相同');
        }
        $orderInfo->design_id = $userId;
        if ($orderName) {
            $orderInfo->order_name = $orderName;
        }
        $orderInfo->save();
        return true;
    }
}